/*
@info 该文件来自windaeam。
*/
console.log("custome-atrr-utils.js");

var FIELD_TYPE = {
	INT: 1,
	DECIMAL: 2,
	DATE: 3,
	DATETIME: 4,
	VARCHAR: 5,
	TEXT: 6,
	SELECT: 7,
	RADIO: 8,
	CHECKBOX: 9,
	ATTACHMENT: 10,
}

var FIELD_TEMPLATES = [{
	id: -FIELD_TYPE.INT,
	icon: 'page/back/customeAttr/img/数值.png',
	name: '整数',
	type: FIELD_TYPE.INT,
	default_value: '',
}, {
	id: -FIELD_TYPE.DATETIME,
	icon: 'page/back/customeAttr/img/时间.png',
	name: '日期时间',
	type: FIELD_TYPE.DATETIME,
	type_ext: 'yyyy-MM-dd hh:mm:ss',
	default_value: 'now()',
}, {
	id: -FIELD_TYPE.VARCHAR,
	icon: 'page/back/customeAttr/img/输入框.png',
	name: '输入框',
	type: FIELD_TYPE.VARCHAR,
	default_value: '',
	col: 6,
}, {
	id: -FIELD_TYPE.TEXT,
	icon: 'page/back/customeAttr/img/文本域.png',
	name: '文本域',
	type: FIELD_TYPE.TEXT,
	default_value: '',
}, {
	id: -FIELD_TYPE.SELECT,
	icon: 'page/back/customeAttr/img/下拉框.png',
	name: '下拉框',
	type: FIELD_TYPE.SELECT,
	type_ext: '选项1,选项2',
	default_value: '',
	col: 6,
}, {
	id: -FIELD_TYPE.RADIO,
	icon: 'page/back/customeAttr/img/单选.png',
	name: '单选框',
	type: FIELD_TYPE.RADIO,
	type_ext: '选项1,选项2',
	default_value: '选项1',
}, {
	id: -FIELD_TYPE.CHECKBOX,
	icon: 'page/back/customeAttr/img/复选.png',
	name: '复选框',
	type: FIELD_TYPE.CHECKBOX,
	type_ext: '&选项1,&选项2',
	default_value: '&选项1',
}];


var __dateFormat = function (date, fmt) { //author: meizz
	var o = {
		"M+": date.getMonth() + 1,                 //月份
		"d+": date.getDate(),                    //日
		"h+": date.getHours(),                   //小时
		"m+": date.getMinutes(),                 //分
		"s+": date.getSeconds(),                 //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
var __ifNil = function (v, v2) {
	return (v === null || v === undefined) ? v2 : v;
}

var __safeStr = function (v) {
	return __ifNil(v, "");
}

function __toDataStr(dataset) {
	var datas = "";
	for (var k in dataset) {
		datas += " data-" + k + "=\'" + __safeStr(dataset[k]) + "\'";
	}
	return datas;
}

function __collectData(e) {
	var datas = {};
	for (var k in e.dataset) {
		datas[k] = __safeStr(e.dataset[k]);
	}
	return datas;
}

function __data2Input(data, attrs, classEtx, ifUseValue) {
	var type = data.type;
	var type_ext = __safeStr(data.type_ext);
	var name = data.name;
	var default_value = __safeStr(ifUseValue ? data.value : data.default_value);
	var required = __safeStr(data.required);
	var html = "";
	
	if (attrs instanceof Function) {
		attrs = attrs(data);
	}
	attrs = attrs || "";
	var readonly = attrs.indexOf("readonly") >= 0;
	var className = " attr-control attr-control-" + type + " ";
	if (classEtx instanceof Function) {
		className = classEtx(className, type, data);
	} else {
		className += " " + __safeStr(classEtx);
	}
	var input = '<input ' + attrs + ' class="' + className + '" ' + (!!default_value ? 'value="' + default_value + '"' : "") + '>';
	if (type == FIELD_TYPE.TEXT) {
		var sty = data.style && data.style.split(";");
		var _sty = "";
		if (sty) {
			for (var i = 4; i < sty.length; i++) {
				if (_sty.length > 0) {
					_sty += ";";
				}
				_sty += sty[i];
			}
		}
		input = '<textarea ' + attrs + ' style="' + _sty + '" class="' + className + '">' + (!!default_value ? default_value : "") + '</textarea>';
	} else if (type == FIELD_TYPE.SELECT) {
		var _str = '<select ' + attrs + ' class="' + className + '"   ' + (readonly ? 'onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;"' : '') + '>';
		if (!required) {
			_str += "<option value=''>未选择</option>";
		}
		if (type_ext) {
			var arr = type_ext.split(",");
			for (var i = 0; i < arr.length; i++) {
				var v = arr[i];
				_str += "<option value='" + v + "' " + (v === default_value ? "selected" : "") + ">" + v + "</option>";
			}
		}
		_str += '</select>';
		input = _str;
	} else if (type == FIELD_TYPE.RADIO) {
		var _str = '<div class="clearfix">';
		if (type_ext) {
			var arr = type_ext.split(",");
			for (var i = 0; i < arr.length; i++) {
				var v = arr[i];
				_str += "<div class='pull-left'><input " + attrs + " class='" + className + "' name='" + name + "' type='radio' value='" + v + "' " + (v === default_value ? "checked" : "") + ">" + "<label>" + v + "</label></div>";
			}
		}
		_str += '</div>';
		input = _str;
	} else if (type == FIELD_TYPE.CHECKBOX) {
		var _str = '<div class="clearfix">';
		if (type_ext) {
			var arr = type_ext.split(",");
			var _vMap = {};
			if (default_value !== undefined && default_value !== null) {
				var _vs = default_value.split(",");
				for (var i = 0; i < _vs.length; i++) {
					_vMap[_vs[i]] = true;
				}
			}
			for (var i = 0; i < arr.length; i++) {
				var v = arr[i];
				_str += "<div class='pull-left'><input " + attrs + " class='" + className + "' name='" + name + "' type='checkbox' value='" + v + "' " + (_vMap[v] ? "checked" : "") + ">" + "<label>" + v + "</label></div>";
			}
		}
		_str += '</div>';
		input = _str;
	} else if (type == FIELD_TYPE.DATETIME || type == FIELD_TYPE.DATE) {
		var format = type_ext || (type == FIELD_TYPE.DATETIME ? "yyyy-MM-dd hh:mm:ss" : "yyyy-MM-dd");
		var _dv = default_value;
		if (_dv && _dv == "now()") {
			var dt = new Date();
			_dv = __dateFormat(dt, format);
		}
		var layFormat = format.replace("hh", "HH");
		input = '<input ' + (readonly ? "" : 'onclick="initLayerDate2(this, null, {show: true, type: \'datetime\', format: \'' + layFormat + '\'});this.onclick=null;"') + '  readonly data-format="' + format + '" ' + attrs + ' class="' + className + '" ' + (!!_dv ? 'value="' + _dv + '"' : "") + ' />';
	}
	return input;
}


var CustomeAttrAdapter = (function () {
	function CustomeAttrAdapter() {
		function Adapter_1() {
			this.postCustomeAttr = function (instance, options) {
				var fields = instance.fields;
				if (!fields || !fields.length) {
					$(options.extInfoEl).hide();
					console.log(instance);
					return;
				}
				$(options.extInfoEl).show();
				for (var i = 0; i < fields.length; i++) {
					var style = fields[i].style;
					$.extend(fields[i], {
						col: parseInt(style.split(";")[0]), offset: parseInt(style.split(";")[1])
						, colIndx: parseInt(style.split(";")[3])
						, rowIndex: parseInt(style.split(";")[2])
					});
				}
				var html = "";
				var groupByRow = iUtils.groupBy(fields, "rowIndex");
				for (var rowIndex in groupByRow) {
					var row = groupByRow[rowIndex];
					row.sort(function (a, b) {
						return a.colIndex > b.colIndex ? 1 : a.colIndex == b.colIndex ? 0 : -1;
					});
					html += "<tr>";
					for (var i = 0; i < row.length; i++) {
						var item = row[i];
						var offset = item.offset;
						var col = item.col;
						if (offset >= 1) {
							html += "<td colspan='" + offset + "'></td>";
						}
						html += "<td style='    white-space: nowrap;'>" + item.name + "</td>";
						var attrs = "" + __safeStr(options && options.control_attrs);
						
						html += "<td class='attr-control-td' colspan='" + (item.col - 1) + "' " + __toDataStr(item) + ">" + __data2Input(item, attrs, function (className, type) {
							if (type != FIELD_TYPE.RADIO && type != FIELD_TYPE.CHECKBOX) {
								return className + " form-control-gx ";
							} else {
								return className;
							}
						}, !!instance.id) + "</td>";
					}
					html += "</tr>";
				}
				$(options["appendTo"]).append(html);
			}
			this.getCustomeAttr = function (errors, options) {
				var attrTds = $(options.extInfoEl).find(".attr-control-td");
				var arr = [];
				for (var i = 0; i < attrTds.length; i++) {
					var attrTd = attrTds.eq(i);
					var data = __collectData(attrTd[0]);
					var value;
					if (data.type == FIELD_TYPE.RADIO) {
						value = attrTd.find(".attr-control:checked").val();
					} else if (data.type == FIELD_TYPE.CHECKBOX) {
						var checkbox = attrTd.find(".attr-control:checked");
						value = "";
						for (var j = 0; j < checkbox.length; j++) {
							if (value.length > 0) {
								value += ",";
							}
							value += checkbox.eq(j).val();
						}
					} else {
						value = attrTd.find(".attr-control").val();
					}
					arr.push({
						id: attrTd.data("id"),
						field_id: attrTd.data("field_id"),
						value: value,
					});
				}
				return arr;
			}
		}
		
		this.adapter1 = function () {
			return new Adapter_1();
		}
	}
	
	return new CustomeAttrAdapter();
})();

function SimpleCustomeAttrInitHelper(url, instanceId, options) {
	var __this = this;
	this.__instanceId = instanceId;
	this.__basedata_id = "";
	this.adapter = null;
	var oldInstanceId = instanceId || "";
	
	this.getOldInstanceId = function () {
		return oldInstanceId;
	}
	
	this.onBasedataSet = function (basedata_id) {
		if (this.__basedata_id && this.__basedata_id == basedata_id) {
			return;
		}
		this.__basedata_id = basedata_id;
		this.__instanceId = instanceId;
		instanceId = "";
		var placeholder = "<tr style='visibility:hidden'>";
		for (var i = 0; i < 12; i++) {
			placeholder += "<td style='height: 1px;'></td>";
		}
		placeholder += "</tr>";
		$(options["appendTo"]).html(placeholder);
		__this.initCustomeAttr(url, basedata_id, __this.__instanceId, options);
	}
	this.appendParamStr = function (fields) {
		return "&custome_attr_instance_id="
			+ (oldInstanceId || "")
			+ "&basedata_id="
			+ (this.__basedata_id || "")
			+ "&custome_attr_fields="
			+ encodeURIComponent(JSON.stringify(fields));
	}
	
	this.initCustomeAttr = function (url, basedata_id, instanceId, options) {
		$.post(url, {basedata_id: basedata_id, instance_id: instanceId}, function (data) {
			if (data.code == 0) {
				__this.postCustomeAttr(data.data, options);
			} else {
//				sys.msg(data);
				$(options.extInfoEl).hide();
			}
		})
	}
	
	this.postCustomeAttr = function (instance, options) {
		__this.adapter = options["adapter"] || CustomeAttrAdapter.adapter1();
		__this.adapter.postCustomeAttr(instance, options);
	}
	
	this.getCustomeAttrIfValidate = function () {
		var errors = [];
		var fields = __this.adapter.getCustomeAttr(errors, options);
		if (errors.length > 0) {
			return false;
		}
		return fields;
	}
	
	if (this.__instanceId) {
		this.onBasedataSet("");
	}
}